/**
 * FormCompar.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormCompar.java
 * Created on 05/04/2009, 10:34:08
 */

package trabpoo;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import plagio.postgres.ConnectionPostgres;
import plagio.utils.ArffGenerate;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import weka.core.Instances;

/**
 *
 * @author jmsandy
 */
public class FormCompar extends javax.swing.JDialog {
    private ConnectionPostgres connection;
    private ResultSet result;
    private String str = "";

    /** Creates new form FormCompar */
    public FormCompar() {
        initComponents();
        DefaultTableCellRenderer align = new DefaultTableCellRenderer();
        align.setHorizontalAlignment(SwingConstants.RIGHT);
        // Setting up all the columns of the table to not allow them to resize.
        tableResult.getColumnModel().getColumn(0).setPreferredWidth(558);
        tableResult.getColumnModel().getColumn(0).setResizable(false);
        tableResult.getColumnModel().getColumn(1).setPreferredWidth(100);
        tableResult.getColumnModel().getColumn(1).setResizable(false);
        tableResult.getColumnModel().getColumn(1).setCellRenderer(align);
        // Adding a combobox to select the language.
        tableResult.getTableHeader().setReorderingAllowed(false);
        tableResult.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tableResult.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        selectFile = new javax.swing.JToggleButton();
        textSelectedFile = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableResult = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Comparation of Texts");
        setBounds(new java.awt.Rectangle(0, 0, 0, 0));
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Selections of files", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("SansSerif", 1, 14))); // NOI18N

        jLabel1.setFont(new java.awt.Font("SansSerif", 0, 12));
        jLabel1.setText("Select a file");

        selectFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/trabpoo/images/search.png"))); // NOI18N
        selectFile.setToolTipText("Select a file");
        selectFile.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        selectFile.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                selectFileMouseClicked(evt);
            }
        });

        textSelectedFile.setFont(new java.awt.Font("DejaVu Sans", 1, 14));
        textSelectedFile.setDisabledTextColor(java.awt.Color.black);
        textSelectedFile.setEnabled(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(textSelectedFile, javax.swing.GroupLayout.PREFERRED_SIZE, 455, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(selectFile, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(textSelectedFile, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(selectFile))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tableResult.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Text", "Percentage %"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableResult.setEnabled(false);
        tableResult.setRowHeight(26);
        jScrollPane1.setViewportView(tableResult);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 663, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleDescription("compar");

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-697)/2, (screenSize.height-372)/2, 697, 372);
    }// </editor-fold>//GEN-END:initComponents

    private void selectFileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_selectFileMouseClicked
        // TODO add your handling code here:
        FormChoice fmChoice = new FormChoice();
        fmChoice.setModal(true);
        fmChoice.setVisible(true);
        textSelectedFile.setText(fmChoice.getFile());

        // Checks if was returned any value of to previous form.
        if(!textSelectedFile.getText().trim().isEmpty()){
            // Show result
            this.str = fmChoice.getText();
            if(mountResult()) showResult();
        }
        fmChoice.dispose();
}//GEN-LAST:event_selectFileMouseClicked

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormCompar().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToggleButton selectFile;
    private javax.swing.JTable tableResult;
    private javax.swing.JTextField textSelectedFile;
    // End of variables declaration//GEN-END:variables
    
    private boolean mountResult(){
        boolean status = false;
        
        try{
            Properties props = System.getProperties();
            props.load(ClassLoader.getSystemResourceAsStream("plagio.properties"));
            connection = new ConnectionPostgres();
            if(connection.connection(props.getProperty("user"),
                props.getProperty("password"),props.getProperty("url"))){
                // Inserting the file imported.
                status = true;
                Statement stat;
                stat = connection.getConnection().createStatement();
                String query = "SELECT * FROM \"FileImport\" WHERE IDFile <> " +
                        this.textSelectedFile.getText().trim().split(" - ")[0];
                result = stat.executeQuery(query);
            }
        }catch(Exception e){
            status = false;
            System.out.print(e.getMessage() + " ");
        }    
        return status;
    }
    
    private void showResult(){
        DefaultTableModel def = (DefaultTableModel)tableResult.getModel();
        def.getDataVector().clear();
        tableResult.updateUI();
        try {
            while(result.next()){
                ArffGenerate arff = new ArffGenerate();
                arff.setText(this.str);
                Instances instances =
                arff.fileArffNominalJoin(result.getString(7).split("\n"),
                        "file");
                Object[] row = new Object[]{result.getString(2), 
                arff.getPercPlagio(instances) + " %"};
                def.addRow(row);
            }
        } catch (Exception ex) {
            System.out.print(ex.getMessage());
        }
    }
}
